package com.syni.mdd.yhd.common.all.quartz.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.entity.SystemUser;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.entity.user.BmsUserRegisterDisaster;
import com.syni.mdd.yhd.common.all.service.BmsCommonService;
import com.syni.mdd.yhd.common.all.service.BmsUserService;
import com.syni.mdd.yhd.common.all.service.user.BmsUserRegisterDisasterService;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.*;

/**
 * @className UserQuartz
 * @description TOO
 * @Author cfx
 * @DATE 2019/9/2 17:34
 * @VERSION 1.0
 **/
//@Component
@EnableScheduling
public class UserQuartz {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    BmsUserService bmsUserService;

    @Autowired
    BmsUserRegisterDisasterService bmsUserRegisterDisasterService;
    
    @Autowired
    RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0 6 * * ?")  //每天6点执行一次定时任务
    //@Scheduled(cron = "0/5 * * * * ?")
    public void initUserConsumption(){
        log.info("..............count userConsumption start.............");
        Date nowTime = new Date();
        //开始时间
        Date startTime = DateTimeUtils.getStartTimeOfDay(DateTimeUtils.addDay(nowTime,-1));
        //Date startTime = new Date(0);
        //结束时间
        Date endTime = DateTimeUtils.getEndTimeOfDay(startTime);
        Map<String,Object> condtionMap = new HashMap<>();
        condtionMap.put("dxshh_NOLIKES","X00999");
        condtionMap.put("newTime_GTTE",startTime);
        condtionMap.put("newTime_LTT",endTime);
        List<BmsUser> bmsUsers = bmsUserService.getBaseDao().findAll(new SpecificationUtils(condtionMap));
        if(bmsUsers != null && bmsUsers.size() > 0){
            for(BmsUser bmsUser : bmsUsers){
                redisTemplate.opsForZSet().incrementScore(Constants.REDIS_KEY_USER_CONSUMPTION,bmsUser.getId(),0d);
            }
        }
    }

    @Scheduled(cron = "0 0 6 * * ?")  //每天6点执行一次定时任务
    public void clearOverreRequestWxBind(){
        //清空一些超过一个星期的记录
        log.info(" >>  clearOverreRequestWxBind   start >> ");
        Map<String,Object> condtionMap = new HashMap<>();
        condtionMap.put("registerWay","3");
        condtionMap.put("isHandle","1");
        condtionMap.put("newTime_LTTE",DateTimeUtils.addDay(new Date(),-7));

        List<BmsUserRegisterDisaster> bmsUserRegisterDisasters = bmsUserRegisterDisasterService.getBaseDao().findAll(new SpecificationUtils(condtionMap));
        if(bmsUserRegisterDisasters != null && bmsUserRegisterDisasters.size() > 0){
            bmsUserRegisterDisasterService.getBaseDao().deleteAll(bmsUserRegisterDisasters);
        }
    }


    
    @Scheduled(cron = "0 0 6 * * ?")  //每天6点执行一次定时任务
    public void reRequestWxBind(){
        //清空一些超过一个星期的记录
        log.info(".............. reRequestWxBind   start.............");
        Map<String,Object> condtionMap = new HashMap<>();
        condtionMap.put("registerWay","3");
        condtionMap.put("isHandle","0");
        List<BmsUserRegisterDisaster> bmsUserRegisterDisasters = bmsUserRegisterDisasterService.getBaseDao().findAll(new SpecificationUtils(condtionMap));
        if(bmsUserRegisterDisasters != null && bmsUserRegisterDisasters.size() > 0){
            for(BmsUserRegisterDisaster bmsUserRegisterDisaster : bmsUserRegisterDisasters){
            	if(StringUtils.checkNullAndEmpty(bmsUserRegisterDisaster.getContent())) {
            		
            	 try {
                 	Map<String,Object> updateParams = new HashMap<>();
                 	updateParams = JSONObject.parseObject(bmsUserRegisterDisaster.getContent());
                     String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/relationWx";
                     JSONObject registerResult = JSONObject.parseObject(RestTemplateUtils.postForEntityForJson(registerUrl,updateParams));
                     String registerStatus = registerResult.getString("status");
//                     JSONObject registerData = registerResult.getJSONObject("data");
                     if ("00".equals(registerStatus)) {
                         log.info("绑定/解绑微信 更新成功");
                         bmsUserRegisterDisaster.setIsHandle(Constants.COMMON_FLAG_TRUE_INT);
                         bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
                     } 
                 } catch (Exception e) {
                     log.error("调用户体系接口出错："+e.getMessage());
                     continue;
                 }
            	}
            }
        }
    }



    @Scheduled(cron = "0 0 6 * * ?")  //每天7点执行一次定时任务
    public void clearUserRegisterDisaster(){
        log.info(" >>  clearUserRegisterDisaster >> start >> ");
        Map<String,Object> condtionMap = new HashMap<>();
        condtionMap.put("registerWay_IN",new HashSet<>(
                Arrays.asList(new Integer[]{Constants.REGISTER_CREATE_NEW_USER,Constants.REGISTER_USER_SYSTEM})));
        condtionMap.put("isHandle",Constants.COMMON_FLAG_TRUE_INT);
        condtionMap.put("remark","");
        condtionMap.put("newTime_LTTE",DateTimeUtils.addDay(new Date(),-7));
        List<BmsUserRegisterDisaster> bmsUserRegisterDisasters = bmsUserRegisterDisasterService.getBaseDao().findAll(new SpecificationUtils(condtionMap));
        if(bmsUserRegisterDisasters != null && bmsUserRegisterDisasters.size() > 0){
            bmsUserRegisterDisasterService.getBaseDao().deleteAll(bmsUserRegisterDisasters);
        }
    }

    @Scheduled(cron = "0 0 7 * * ?")  //每天7点执行一次定时任务
    public void userRegisterDisaster(){
        log.info(".............. userRegisterDisaster   start.............");
        Map<String,Object> condtionMap = new HashMap<>();
        condtionMap.put("registerWay_IN",new HashSet<>(
                Arrays.asList(new Integer[]{Constants.REGISTER_CREATE_NEW_USER,Constants.REGISTER_USER_SYSTEM})));
        condtionMap.put("isHandle","0");
        Pageable pageable = BmsCommonService.getPageable(1,100);
        List<BmsUserRegisterDisaster> bmsUserRegisterDisasters = bmsUserRegisterDisasterService.getBaseDao().findAll(new SpecificationUtils(condtionMap),pageable).getContent();
        if(bmsUserRegisterDisasters != null && bmsUserRegisterDisasters.size() > 0){
            for(BmsUserRegisterDisaster bmsUserRegisterDisaster : bmsUserRegisterDisasters){
                if(StringUtils.isNotBlank(bmsUserRegisterDisaster.getContent())) {
                    try {
                        if(bmsUserRegisterDisaster.getRegisterWay() == Constants.REGISTER_CREATE_NEW_USER){
                            Map<String,Object> paramsModel = JSON.parseObject(bmsUserRegisterDisaster.getContent());
                            String model = paramsModel.get("model").toString();
                            String phone = paramsModel.get("phone").toString();
                            String pwd = paramsModel.get("pwd").toString();
                            Map<String,Object> registerMap = bmsUserService.registerOperHand(phone,pwd,model);
                            if(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString())){
                                Map<String,Object> userMap = (Map<String, Object>) registerMap.get("data");
                                String accountId = userMap.get("accountId").toString();
                                BmsUser bmsUser = TokenManager.getUser(bmsUserRegisterDisaster.getUserId());
                                if(bmsUser != null){
                                    bmsUser.setAccountId(accountId);
                                    TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
                                    bmsUserRegisterDisaster.setIsHandle(Constants.COMMON_FLAG_TRUE_INT);
                                    continue;
                                }
                                if(bmsUser == null){
                                    //通过手机号去找
                                    if(StringUtils.isNotBlank(phone)){
                                        BmsUser phoneUser = bmsUserService.findByPhone(phone);
                                        if(phoneUser == null){
                                            bmsUserRegisterDisaster.setRemark("根据电话号查不到这条记录，需人工解决");
                                            bmsUserRegisterDisaster.setIsHandle(Constants.COMMON_FLAG_TRUE_INT);
                                            continue;
                                        }
                                        if(StringUtils.isBlank(phoneUser.getAccountId())) {
                                            phoneUser.setAccountId(accountId);
                                            TokenManager.setUser(phoneUser);
                                        } else if (phoneUser.getAccountId().equals(bmsUserRegisterDisaster.getAccountId())) {
                                            phoneUser.setAccountId(accountId);
                                            TokenManager.setUser(phoneUser);
                                        }else if(phoneUser.getAccountId().equals(accountId)){
                                            ;
                                        }else {
                                            bmsUserRegisterDisaster.setRemark("觅东东用户端和用户体系accountId无法同步，需人工解决");
                                        }
                                        bmsUserRegisterDisaster.setIsHandle(Constants.COMMON_FLAG_TRUE_INT);
                                    }
                                }
                            }
                        }else if(bmsUserRegisterDisaster.getRegisterWay() == Constants.REGISTER_USER_SYSTEM){
                            SystemUser systemUser = JSON.parseObject(bmsUserRegisterDisaster.getContent(),SystemUser.class);
                            Map<String, Object> registerRet = WeChartUtils.addUserToUserSystem(systemUser,true);
                            JSONObject registerData = (JSONObject) registerRet.get("data");
                            String accountId = null;
                            String loginName = null;
                            String headImgUrl = null;
                            if (registerData.containsKey("accountId")) {
                                accountId = registerData.getString("accountId");
                            }
                            if(StringUtils.isBlank(accountId)){
                                bmsUserRegisterDisaster.setIsHandle(Constants.COMMON_FLAG_TRUE_INT);
                                bmsUserRegisterDisaster.setAccountId("用户体系unionId下的accountId无法获取");
                                continue;
                            }
                            if (registerData.containsKey("loginName")) {
                                loginName = registerData.getString("loginName");
                            }
                            if (registerData.containsKey("headImgUrl")) {
                                headImgUrl = registerData.getString("headImgUrl");
                            }
                            if ((boolean) registerRet.get("status")) {
                                BmsUser bmsUser = TokenManager.getUser(bmsUserRegisterDisaster.getUserId());
                                if(bmsUser == null){
                                    Map<String,Object> paramsModel = JSON.parseObject(bmsUserRegisterDisaster.getContent());
                                    if(paramsModel.containsKey("unionId")) {
                                        String unionId = paramsModel.get("unionId").toString();
                                        BmsUser unionUser = bmsUserService.findUserByUnionId(unionId);
                                        if(unionUser == null){
                                            bmsUserRegisterDisaster.setRemark("找不到对应的unionId");
                                        }
                                        else if(StringUtils.isBlank(unionUser.getAccountId()) && StringUtils.isNotBlank(accountId)){
                                            unionUser.setAccountId(accountId);
                                            TokenManager.setUser(unionUser);
                                        }else if(StringUtils.isNotBlank(accountId) && accountId.equals(unionUser.getAccountId())){
                                            ;
                                        }else if(StringUtils.isNotBlank(accountId) && !accountId.equals(unionUser.getAccountId())){
                                            bmsUserRegisterDisaster.setRemark("觅东东用户体系和用户体系unionId下的accountId无法进行对应");
                                        }else if(StringUtils.isNotBlank(accountId) && unionUser.getAccountId().equals(bmsUserRegisterDisaster.getAccountId())){
                                            unionUser.setAccountId(accountId);
                                            TokenManager.setUser(unionUser);
                                        }
                                    }
                                } else {
                                    if (StringUtils.isNotBlank(accountId)) {
                                        bmsUser.setAccountId(accountId);
                                    }
                                    if (StringUtils.isNotBlank(loginName)) {
                                        bmsUser.setLoginName(loginName);
                                    }
                                    if (StringUtils.isNotBlank(headImgUrl)) {
                                        bmsUser.setLoginName(headImgUrl);
                                    }
                                    TokenManager.setUser(bmsUser);
                                }
                                bmsUserRegisterDisaster.setIsHandle(Constants.COMMON_FLAG_TRUE_INT);
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(),e);
                    }
                }
            }
            bmsUserRegisterDisasterService.getBaseDao().saveAll(bmsUserRegisterDisasters);
        }
    }
}
